package work5;

import java.io.*;

public class Copy extends Thread {
    private File srcFile;
    private File destFile;

    public Copy(File srcFile, File destFile) {
        this.srcFile = srcFile;
        this.destFile = destFile;
    }

    @Override
    public void run() {
        try (
                FileInputStream fis = new FileInputStream(srcFile);
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {
            long totalBytes = srcFile.length();
            long copiedBytes = 0;
            byte[] buffer = new byte[1024 * 10];
            int len;
            int lastPercent = 0;

            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                copiedBytes += len;
                
                int percent = (int)((copiedBytes * 100) / totalBytes);
                if (percent != lastPercent) {
                    System.out.println(srcFile.getName() + " 已复制 " + percent + "%");
                    lastPercent = percent;
                }
            }

            System.out.println(srcFile.getName() + " 复制完成！");
        } catch (IOException e) {
            System.out.println("复制出错：" + srcFile.getName());
            throw new RuntimeException(e);
        }
    }

}
